//
//  HTClassImageLocalStorage.swift
//  QuitSmokingApp
//
//  Created by wealon on 2024.
//  QuitSmokingApp.
//


import Foundation
import UIKit

class HTClassImageLocalStorage {
    static func ht_saveImageToLocal(var_image: UIImage, var_key: String) {
        let var_picPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/\(var_key).png"
        print("将图片保存到本地  \(var_picPath)")
        
//        if ht_localHaveImage(var_key: var_key) {
//            print("本地已经保存该图片、无需再次存储...")
//            return
//        }
        
        guard let var_imgData = var_image.jpegData(compressionQuality: 0.5) else { return }
        try? var_imgData.write(to: URL(fileURLWithPath: var_picPath), options: .atomic)
    }
    
    static func ht_getImageFromLocal(var_key: String) -> UIImage? {
        if var_key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
            return nil
        }
        
        let var_picPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/\(var_key).png"
        print("获取图片   \(var_picPath)")
        
        return UIImage(contentsOfFile: var_picPath)
    }
    
    static func ht_localHaveImage(var_key: String) -> Bool {
        if var_key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
            return false
        }
        
        let var_picPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/\(var_key).png"
        print("查询是否存在 \(var_picPath)")
        
        return FileManager.default.fileExists(atPath: var_picPath)
    }
    
    static func ht_removeImageFromLocalKeys(var_key: String) {
        let var_picPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/\(var_key).png"
        print("将图片从本地删除  \(var_picPath)")
        
        try? FileManager.default.removeItem(atPath: var_picPath)
    }
}
